import 'dart:io';
import 'dart:async';

import 'package:args/command_runner.dart';
import 'package:gate_cli/exception/errors.dart';
import 'package:gate_cli/utils/print.dart';

/// Author: Shper
/// Created: 2023/9/1
class PubCommand extends Command<String> {

  @override
  String get description => '更新 pub 依赖';

  @override
  String get name => 'pub';

  PubCommand() {
    // 操作符
    // argParser.addCommand('get');
    argParser.addOption('get', help: 'flutter pub get');
    argParser.addOption('upgrade', help: 'flutter pub upgrade');
    // 平台
    argParser.addOption('all', help: '更新全部平台');
    argParser.addOption('iOS', abbr: 'i', help: '只更新 iOS相关的');
    argParser.addOption('android', abbr: 'a', help: '只更新 Android 相关的');
  }

  @override
  FutureOr<String>? run() {
    // 获取参数
    String pubOperator = argResults?['get'] ?? 'upgrade';
    String platform = argResults?['android'] ?? 'all';
    platform = argResults?['iOS'] ?? 'all';

    String projectDirectoryPath = Directory.current.path;
    print('当前目录：$projectDirectoryPath');
    print('开始更新项目 pub 依赖....');

    var result = syncFlutterPub(pubOperator, workingDirectory: projectDirectoryPath);
    if (!result) {
      throw new CommandRunError("flutter pub ${pubOperator} is running error.");
    }

    var exampleDirectory = Directory(projectDirectoryPath + "/example");
    if (exampleDirectory.existsSync()) {
      print('开始更新 Example 的 pub 依赖....');
      print('Example 目录：${exampleDirectory.path}');

      var exampleResult = syncFlutterPub(pubOperator, workingDirectory: exampleDirectory.path);
      if (!exampleResult) {
        throw new CommandRunError("The Example's flutter pub ${pubOperator} is running error.");
      }

      if (platform == 'all' || platform == 'iOS') {
        print('开始更新 iOS Example pod....');
        // pod install --project-directory=$projectPath/example/ios
        final iOSPodResult = Process.runSync('pod', ['install'], workingDirectory: exampleDirectory.path + "/ios", runInShell: true);
        if (iOSPodResult.exitCode != 0) {
          print(iOSPodResult.stderr);
          throw new CommandRunError("The iOS Example's pod install is running error.");
        }
      }
    }

    printGreen('依赖更新完成~');
    return "Success";
  }

  bool syncFlutterPub(String pubOperator, {String? workingDirectory}) {
    if (pubOperator == 'upgrade') {
      printYellow('清除 Flutter 项目缓存');
      final cleanResult = Process.runSync('flutter', ['clean'], workingDirectory: workingDirectory, runInShell: true);
      print(cleanResult.stdout);
    }

    final upgradeResult = Process.runSync('flutter', ['pub', pubOperator], workingDirectory: workingDirectory, runInShell: true);
    print(upgradeResult.stdout);

    if (upgradeResult.exitCode != 0) {
      printRed(upgradeResult.stderr);
      return false;
    }

    return true;
  }

}
